package com.springcloudemo.ms;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Yangdw
 * @date 2025-08-20
 * @description: 全局过滤器
 */
@Component
public class LoggerGlobalFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getAttributes().put("Start_Time",System.currentTimeMillis());
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            //处理请求之后也可以干点事情
            Long start_time = exchange.getAttribute("Start_Time");

            if (start_time != null){
                long endTime = System.currentTimeMillis();
                long cost = endTime - start_time;
                System.out.println("请求地址: "+exchange.getRequest().getURI()
                        + " 耗时为: "+cost+ " 毫秒");
            }
        }));
    }
}
